package com.sdkj.recruit.service.impl;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mongodb.gridfs.GridFSDBFile;
import com.sdkj.recruit.dao.IGridFsDAO;
import com.sdkj.recruit.dao.IMongodbDAO;
import com.sdkj.recruit.model.FileTest;
import com.sdkj.recruit.service.IFileService;
import com.sdkj.recruit.util.FileUtil;
import com.sdkj.recruit.util.UtilHelper;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

@Service
public class FileService implements IFileService {

	@Autowired
	private IMongodbDAO dao;

	@Autowired
	private IGridFsDAO grid;

	@Override
	public void saveFile(String name, File file) {

		FileTest f = new FileTest();
		f.setFileName(name);
		f.setBase64(getImageBinary(file));
		dao.saveOrUpdatePO(f);
	}

	public String getImageBinary(File f) {

		BASE64Encoder encoder = new BASE64Encoder();
		BufferedImage bi;
		try {
			bi = ImageIO.read(f);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ImageIO.write(bi, "jpg", baos); // 经测试转换的图片是格式这里就什么格式，否则会失真
			byte[] bytes = baos.toByteArray();
			return encoder.encodeBuffer(bytes).trim();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public void base64StringToImage(String base64String, String path, String name) {
		try {
			BASE64Decoder decoder = new sun.misc.BASE64Decoder();

			byte[] bytes1 = decoder.decodeBuffer(base64String);

			ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
			BufferedImage bi1 = ImageIO.read(bais);
			File w2 = new File(path + name);// 可以是jpg,png,gif格式
			ImageIO.write(bi1, "jpg", w2);// 不管输出什么格式图片，此处不需改动
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void getFile(String fileId) {

		FileTest file = dao.getPO(FileTest.class, fileId);
		base64StringToImage(file.getBase64(), "F:\\data10\\get\\", file.getFileName());
	}

	@Override
	public void saveGridFile(File f) {
		try {
			String id = grid.storeFile(new FileInputStream(f), f.getName());
			System.out.println(id);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void getFileGrid(String fileId) {
		GridFSDBFile grid1 = grid.getFile(fileId);

		FileUtil.getFileGrid(grid1, "F:\\data10\\get", grid1.getFilename());
	}

	@Override
	public void getFileByte(String fileId) {

		FileTest file = dao.getPO(FileTest.class, fileId);
		String base64 = UtilHelper.byte2Base64StringFun(file.getFileByte());
		base64StringToImage(base64, "F:\\data10_test\\", file.getFileName());

	}
}
